<template>
	<view class="my_add_path">
		<u-navbar :title="title" @leftClick="leftClick" :autoBack="true" placeholder>
		</u-navbar>

		<view class="path-item Row">
			<view class="left">收件人</view>
			<input class="input" type="text" placeholder="收件人姓名" :value="pathObj.name" data-pathObj="name"
				@input="input" />
		</view>
		<view class="path-item Row">
			<view class="left">手机号</view>
			<input class="input" type="number" placeholder="手机号" :value="pathObj.mobile" data-pathObj="mobile"
				@input="input" />
		</view>
		<view class="path-item Row">
			<view class="left">所在地址</view>
			<view class="input Row">
				<picker data-area="province" @change="bindPickerChange" :value="provinceIndex" :range="provinceCopy">
					<view class="uni-input">{{provinceCopy[provinceIndex]}}</view>
				</picker>
				<picker data-area="city" @change="bindPickerChange" :value="cityIndex" :range="cityCopy">
					<view class="uni-input">{{cityCopy[cityIndex]}}</view>
				</picker>
				<picker data-area="region" @change="bindPickerChange" :value="regionIndex" :range="regionCopy">
					<view class="uni-input">{{regionCopy[regionIndex]}}</view>
				</picker>
			</view>
		</view>
		<view class="path-item Row" style="align-items: flex-start;">
			<view class="left" style="padding-top: 10px;">详细地址</view>
			<textarea class="input" cols="30" rows="10" placeholder="5到60个字符" :value="pathObj.address"
				data-pathObj="address" @input="input"></textarea>
		</view>

		<!-- 选择收货地址的盒子 -->
		<view class="addressChoose Row">
			<button style="background: #0056FF;" type="primary" size="mini" class="btn" @click="addAddress">保存</button>
		</view>
	</view>
</template>

<script>
	import {
		postMenu,
		getMenu
	} from '@/utils/api.js';
	import {
		apiAddAddress,
		apiAreaList,
		apiEditAddress,
		apiAddressDetail
	} from '@/api/order.js';

	export default {
		data() {
			return {
				title: "收货地址",
				id: null,

				provinceCopy: ['请选择'], //省区数组
				provinceIndex: 0, //省区下标

				province: ['请选择'],
				provinceVal: '',

				cityCopy: ['请选择'], //市区数组
				cityIndex: 0, //市区下标

				city: ['请选择'],
				cityVal: '',

				regionCopy: ['请选择'], //市区数组
				regionIndex: 0, //市区下标

				region: ['请选择'],
				regionVal: '',

				pathObj: {
					name: "",
					mobile: "",
					address: ""
				},
			};
		},
		onLoad(options) {
			if (options.id) {
				this.title = "编辑地址";
				this.id = options.id;
				this.getAddressDetail(options.id); // 获取地址信息
			} else {
				this.title = "新增地址";
				this.getArea();
				this.getcity();
				this.getRegion();
			}
		},
		methods: {
			leftClick() {
				// uni.navigateBack()
			},

			getAddressDetail(id) {
				uni.showLoading({
					title: '加载中'
				});

				let addressData = null;

				apiAddressDetail({
						params: {
							id
						}
					})
					.then(res => {
						uni.hideLoading();

						if (!res.code) {
							uni.$u.toast('获取地址失败');
							return Promise.reject(new Error('接口错误'));
						}

						addressData = res.data;

						this.pathObj = {
							name: addressData.name,
							mobile: addressData.mobile,
							address: addressData.detail
						};

						return this.getArea();
					})
					.then(() => {
						// 先设置 provinceVal，即使找不到 index 也继续加载城市
						this.provinceVal = addressData.province_id;

						// 查找 index
						const provinceIndex = this.province.findIndex(p => p.value === String(addressData
							.province_id));
						this.provinceIndex = provinceIndex !== -1 ? provinceIndex : 0;
						console.log("省份邮编" + this.provinceVal, "省份下标" + this.provinceIndex);

						// 无论如何都加载城市数据
						return this.getcity(addressData.province_id); // 强制传入 province_id
					})
					.then(() => {
						// 同样处理 cityIndex
						this.cityVal = addressData.city_id;

						const cityIndex = this.city.findIndex(c => c.value === String(addressData.city_id));
						this.cityIndex = cityIndex !== -1 ? cityIndex : 0;
						console.log("市份邮编" + this.cityVal, "市份下标" + this.cityIndex);

						// 加载区县
						return this.getRegion(addressData.city_id);
					})
					.then(() => {
						// 处理区县 index
						this.regionVal = addressData.district_id;

						const regionIndex = this.region.findIndex(r => r.value === String(addressData.district_id));
						this.regionIndex = regionIndex !== -1 ? regionIndex : 0;
						console.log("区份邮编" + this.regionVal, "区份下标" + this.regionIndex);
					})
					.catch(err => {
						uni.hideLoading();
						uni.$u.toast('网络异常，请重试');
					});
			},

			input(e) {
				const val = e.detail.value.trim();
				const name = e.currentTarget.dataset.pathobj;
				this.pathObj[name] = val;
			},

			addAddress() {
				let that = this;
				if (!that.pathObj.name) return uni.$u.toast("请输入收件人");
				if (!that.pathObj.mobile) return uni.$u.toast("请输入手机号");
				if (!that.pathObj.address) return uni.$u.toast("请输入详细地址");

				// 构造参数
				const params = {
					province_id: that.provinceVal,
					city_id: that.cityVal,
					district_id: that.regionVal,
					name: that.pathObj.name,
					mobile: that.pathObj.mobile,
					detail: that.pathObj.address
				};

				// 判断调用哪个接口
				let apiCall;
				if (that.title === "编辑地址") {
					apiCall = apiEditAddress({
						id: that.id,
						...params
					});
				} else {
					apiCall = apiAddAddress(params);
				}

				// 统一处理结果
				apiCall
					.then(res => {
						if (res.code == 0) {
							uni.$u.toast(res.msg);
							return;
						}
						uni.$u.toast("提交成功");
						setTimeout(function() {
							uni.navigateBack({
								delta: 1
							})
						}, 500)
					}).catch(err => console.log(err))
			},

			bindPickerChange(e) {
				const value = e.detail.value;
				const area = e.currentTarget.dataset.area;

				if (area === 'province') {
					this.provinceIndex = value;
					this.provinceVal = this.province[value]?.value || '';

					this.cityCopy = [];
					this.regionCopy = [];
					this.cityIndex = 0;
					this.regionIndex = 0;

					this.getcity();
				} else if (area === 'city') {
					this.cityIndex = value;
					this.cityVal = this.city[value]?.value || '';

					this.regionCopy = [];
					this.regionIndex = 0;

					this.getRegion();
				} else if (area === 'region') {
					this.regionIndex = value;
					this.regionVal = this.region[value]?.value || '';
				}
			},

			getArea() {
				return apiAreaList()
					.then(res => {
						let newObject = {
							value: '',
							name: '请选择'
						};
						res.data.unshift(newObject);

						// 使用 $set 更新数组，确保响应式
						this.province = res.data;
						this.$set(this, 'provinceCopy', res.data.map(item => item.name));
						this.provinceVal = this.province[0]?.value || '';
					})
					.catch(err => console.log(err));
			},

			getcity(code = this.provinceVal) {
				if (!code) return Promise.resolve();

				return apiAreaList({
						params: {
							code
						}
					})
					.then(res => {
						let newObject = {
							value: '',
							name: '请选择'
						};
						res.data.unshift(newObject);

						this.city = res.data;
						this.$set(this, 'cityCopy', res.data.map(item => item.name));
						this.cityVal = this.city[0]?.value || '';
					})
					.catch(err => console.log(err));
			},

			getRegion(code = this.cityVal) {
				if (!code) return Promise.resolve();

				return apiAreaList({
						params: {
							code
						}
					})
					.then(res => {
						let newObject = {
							value: '',
							name: '请选择'
						};
						res.data.unshift(newObject);

						this.region = res.data;
						this.$set(this, 'regionCopy', res.data.map(item => item.name));
						this.regionVal = this.region[0]?.value || '';
					})
					.catch(err => console.log(err));
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F5F6F8;
	}

	.my_add_path {
		background-color: #fff;
		padding: 24rpx;

		.path-item {
			justify-content: space-between;
			padding: 16rpx 0;

			.left {
				width: 20%;
				display: flex;
			}

			.input {
				justify-content: space-around;
				width: 480rpx;
				border-radius: 10rpx;
				background-color: #fbfbfb;
				padding: 20rpx;

				.uni-input {
					margin-left: 16rpx;
				}
			}
		}

		.addressChoose {
			z-index: 3;
			width: 96.4%;
			background-color: #fff;
			padding: 20rpx;
			position: fixed;
			left: 0;
			bottom: 0;

			.btn {
				width: 94%;
				font-size: 30rpx;
				border: none;
				border-radius: 40rpx;
				padding: 6rpx 0;
			}
		}
	}
</style>